<?php
/**
 * Created by PhpStorm.
 * User: Vagrant Archer
 * Date: 2017/8/10
 * Time: 10:22
 */

use yii\db\Connection;
use yii\db\Command;
use yii\db\Query;
use yii\di\Instance;

class CarrierDB extends Carrier
{
	private $dbHg = "";	//todo:后续改成根据historiographer确定

	public function __construct(string $hgToken = "dbHeimdallLog")
	{
		parent::__construct();
		$this->dbHg	=	$hgToken;
		$this->dbHg	=	Instance::ensure($this->dbHg, Connection::className());
	}

	public function fetch()
	{
		$command = $this->dbHg->createCommand("SELECT DISTINCT(aiNo) FROM afterimageLog");
		$query	 =	$command->queryAll();

		foreach ($query as $aiItem) {
			$aiNo = $aiItem['aiNo'];
			$lastPutTime = date("Y-m-d H:i:s", max ($this->getLastTime($aiNo), time()- __CARRIER_MAX_INTERVAL__ ));   //__CARRIER_MAX_INTERVAL__秒前的就不要了，报警也没有意义。主要用于初始数据加载
			$sqlCommand	=	"SELECT aiTime, aiStatus, aiElapsedTime, aiReturnCode FROM afterimageLog WHERE aiTime > '{$lastPutTime}'  AND aiNo = {$aiNo} ORDER BY aiTime DESC LIMIT 0,".__CARRIER_MAX_LOAD__."\n";
			$commandIn = $this->dbHg->createCommand($sqlCommand);
			$queryIn = $commandIn->queryAll();
			$queryIn = array_reverse($queryIn);

			foreach ($queryIn as $item) {
				$afterImage	=	new AfterImage();
				$afterImage->setAiNumber($aiNo);
				$afterImage->setAiTime(strtotime($item['aiTime']));
				$afterImage->setAiStatus($item['aiStatus']);
				$afterImage->setAiElapsedTime($item['aiElapsedTime']);
				$afterImage->setAiReturnCode(explode("||", $item['aiReturnCode'], 5));
				$this->put($afterImage);

			}
		}
	}
}